package com.atguigu.gulimall.ware.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.exception.NoStockException;
import com.atguigu.common.to.mq.OrderTo;
import com.atguigu.common.to.mq.StockDetailTo;
import com.atguigu.common.to.mq.StockLockedTo;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.ware.dao.WareSkuDao;
import com.atguigu.gulimall.ware.entity.WareOrderTaskDetailEntity;
import com.atguigu.gulimall.ware.entity.WareOrderTaskEntity;
import com.atguigu.gulimall.ware.entity.WareSkuEntity;
import com.atguigu.gulimall.ware.feign.OrderFeignService;
import com.atguigu.gulimall.ware.feign.ProductFeignService;
import com.atguigu.gulimall.ware.service.WareOrderTaskDetailService;
import com.atguigu.gulimall.ware.service.WareOrderTaskService;
import com.atguigu.gulimall.ware.service.WareSkuService;
import com.atguigu.gulimall.ware.vo.OrderItemVo;
import com.atguigu.gulimall.ware.vo.OrderVo;
import com.atguigu.gulimall.ware.vo.SkuHasStockVo;
import com.atguigu.gulimall.ware.vo.WareSkuLockVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.Data;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {

    @Autowired
    WareSkuDao wareSkuDao;

    @Autowired
    WareOrderTaskService orderTaskService;

    @Autowired
    WareOrderTaskDetailService orderTaskDetailService;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    OrderFeignService orderFeignService;

    @Autowired
    RabbitTemplate rabbitTemplate;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<WareSkuEntity> queryWrapper = new QueryWrapper<>();
        //一级筛选条件仓库
        String skuId = (String) params.get("skuId");
        if (!StringUtils.isEmpty(skuId)) {
            queryWrapper.eq("sku_id", skuId);
        }

        //二级筛选条件skuId
        String wareId = (String) params.get("wareId");
        if (!StringUtils.isEmpty(wareId)) {
            queryWrapper.eq("ware_id", wareId);
        }

        //分页查询
        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params), queryWrapper
        );
        return new PageUtils(page);
    }

    //采购完成后，修改需要采购的商品的各个信息
    @Override
    public void addStock(Long skuId, Long wareId, Integer skuNum) {
        //判断这个库存记录是否存在
        List<WareSkuEntity> entities = wareSkuDao.selectList(new QueryWrapper<WareSkuEntity>()
                .eq("sku_id", skuId).eq("ware_id", wareId));
        //如果不存在
        if (entities == null || entities.size() == 0) {
            //就创建并插入这条库存记录
            WareSkuEntity skuEntity = new WareSkuEntity();
            //设置各项信息
            skuEntity.setSkuId(skuId);
            skuEntity.setWareId(wareId);
            skuEntity.setStock(skuNum);
            //默认新记录库存为0
            skuEntity.setStockLocked(0);

            //TODO 远程查询sku的名字
            // 如果失败，整个事务无需回滚
            //1、自己catch异常
            //2、TODO 还有什么方法可以让异常出现之后不回滚？
            try {
                R info = productFeignService.info(skuId);
                Map<String, Object> data = (Map<String, Object>) info.get("skuInfo");
                if (info.getCode() == 0) {
                    skuEntity.setSkuName((String) data.get("skuName"));
                }
            } catch (Exception e) {

            }
            wareSkuDao.insert(skuEntity);
        } else {
            //如果之前就存在的话，就修改记录即可
            wareSkuDao.addStock(skuId, wareId, skuNum);
        }
    }

    /**
     * 根据skuId查询是否有库存
     * @param skuIds
     * @return
     */
    @Override
    public List<SkuHasStockVo> getSkuHasStock(List<Long> skuIds) {
        List<SkuHasStockVo> collect = skuIds.stream().map(skuId -> {
            SkuHasStockVo vo = new SkuHasStockVo();
            //查询当前sku的总库存量
            //SELECT SUM(stock-stock_locked) FROM vms_ware_sku WHERE sku_id=1
            Long count = baseMapper.getStuStock(skuId);
            vo.setSkuId(skuId);
            vo.setHasStock(count == null ? false : count > 0);
            return vo;
        }).collect(Collectors.toList());
        return collect;
    }

    /**
     * 为每个订单锁定库存
     * (rollbackFor = NoStockException.class)
     * 默认只要是运行时异常都会回滚
     * 订单需要解锁库存的业务场景
     * 1. 下订单成功，订单过期没有支付被系统自动取消、被用户手动取消，都要解锁库存
     * <p>
     * 2. 下订单成功，库存也锁定成功，接下来的业务调用失败，导致订单回滚。
     * 之前锁定的库存就要自动解锁
     *
     * @param vo 要锁定库存的订单项
     * @return
     */
    @Transactional
    @Override
    public Boolean orderLockStock(WareSkuLockVo vo) {
        //保存库存工作单的详情，便于追溯
        WareOrderTaskEntity taskEntity = new WareOrderTaskEntity();
        taskEntity.setOrderSn(vo.getOrderSn());
        orderTaskService.save(taskEntity);

        //1、安装下单的收货地址，找到一个就近仓库，锁定库存
        //1、找到每个商品在哪个仓库都有库存
        List<OrderItemVo> locks = vo.getLocks();
        List<SkuWareHasStock> collect = locks.stream().map(item -> {
            SkuWareHasStock stock = new SkuWareHasStock();
            //获取参数中要锁商品项的内容
            Long skuId = item.getSkuId();
            stock.setSkuId(skuId);
            stock.setNum(item.getCount());
            //查询这个商品在哪里有库存
            List<Long> wareIds = wareSkuDao.listWareIdHasSkuStock(skuId);
            stock.setWareId(wareIds);
            return stock;
        }).collect(Collectors.toList());

        //2、锁定库存
        for (SkuWareHasStock hasStock : collect) {
            //某一项商品是否锁住库存
            Boolean skuStocked = false;
            Long skuId = hasStock.getSkuId();
            List<Long> wareIds = hasStock.getWareId();
            //没有任何仓库有这个商品的库存,其他商品也不用继续锁库存了
            if (wareIds == null && wareIds.size() == 0) {
                throw new NoStockException(skuId);
            }
            //有库存就锁定
            //1、如果每一个商品都锁定成功，将当前商品锁定了几件的工作单记录发送给MQ
            //2、如果有一个锁定失败，前面的工作信息就回滚了。发送出去的消息，即使要解锁记录，
            // 由于去数据库查不到id，就不用解锁记录
            for (Long wareId : wareIds) {
                //成功就返回1（影响1行），否则为0
                Long count = wareSkuDao.lockSkuStock(skuId, wareId, hasStock.getNum());
                if (count == 1) {
                    skuStocked = true;
                    //当前商品已在某一仓库中锁住库存，不再尝试其他仓库
                    //创建并保存锁定库存工作单
                    WareOrderTaskDetailEntity entity = new WareOrderTaskDetailEntity(null, skuId, "", hasStock.getNum(), taskEntity.getId(), wareId, 1);
                    orderTaskDetailService.save(entity);
                    //告诉MQ哪一个库存工作单锁定了多少商品信息
                    StockLockedTo lockedTo = new StockLockedTo();
                    lockedTo.setId(taskEntity.getId());
                    StockDetailTo stockDetailTo = new StockDetailTo();
                    BeanUtils.copyProperties(entity, stockDetailTo);
                    //只发送id不行，防止回滚以后找不到数据
                    lockedTo.setDetail(stockDetailTo);
                    //TODO 告诉MQ库存锁定成功
                    //向交换机发送库存锁定成功的消息
                    rabbitTemplate.convertAndSend("stock-event-exchange", "stock.locked", lockedTo);
                    break;
                } else {
                    //重试下一个仓库
                }
            }
            if (skuStocked == false) {
                //当前商品试遍了所有仓库，均没有锁住库存
                //提示没库存，其他商品也不用锁了
                throw new NoStockException(skuId);
            }
        }
        //3、全部商品都锁定成功
        return true;
    }

    //释放已锁定的库存，库存自动解锁

    /**
     * 1. 下订单成功，订单过期没有支付被系统自动取消、被用户手动取消，都要解锁库存
     * 2. 下订单成功，库存也锁定成功，接下来的业务调用失败，导致订单回滚。
     * 之前锁定的库存就要自动解锁
     */
    @Override
    public void unLockStock(StockLockedTo to) {
        System.out.println("收到解锁库存的消息");
        StockDetailTo detail = to.getDetail();
        Long detailId = detail.getId();
        //查询数据库关于这个订单的锁定库存信息
        WareOrderTaskDetailEntity byId = orderTaskDetailService.getById(detailId);
        //如果有，正面库存锁定成功了
        /**
         * 解锁要根据订单情况：
         *      1、没有这个订单，必须解锁
         *      2、有这个订单，要根据订单状态
         *          已取消：解锁库存
         *          没取消：不能解锁
         *
         * 解锁库存会失败，所以一定要告诉服务收到消息，不能直接就将消息删除
         */
        if (byId != null) {
            Long id = to.getId();
            //从库存工作单中获取订单号
            WareOrderTaskEntity taskEntity = orderTaskService.getById(id);
            //根据订单号远程查询订单状态
            String orderSn = taskEntity.getOrderSn();
            R r = orderFeignService.getOrderStatus(orderSn);
            if (r.getCode() == 0) {
                OrderVo data = r.getData(new TypeReference<OrderVo>() {
                });
                if (data == null || data.getStatus() == 4) {
                    //订单不存在（库存服务锁定成功，订单自身业务导致其进行了回滚）
                    //订单已经被取消，才能解锁库存
                    if (byId.getLockStatus() == 1){
                        //当前工作单状态为1已锁定但是未解锁，才可以解锁
                        unLockStock(detail.getSkuId(), detail.getWareId(), detail.getSkuNum(), detailId);
                    }
                }
            } else {
                //消息拒绝以后重新放回到队列里面，让别人继续消费解锁（可能本次解锁出问题了,不然也可能会删除消息）
                throw new RuntimeException("远程服务失败");
            }
        } else {
            //无需解锁
        }
    }

    //防止订单服务卡顿，导致订单状态信息一直改变不了，库存信息优先到期。查订单状态还是新建状态，什么都不做就把消息消费了
    //导致卡顿的订单，永远不能解锁库存
    //有一项库存解锁失败，则全部解锁失败
    @Transactional
    @Override
    public void unLockStock(OrderTo orderTo) {
        String orderSn = orderTo.getOrderSn();
        //查一下最新库存的状态，防止之前解锁过了造成重复解锁库存
        WareOrderTaskEntity task = orderTaskService.getOrderTaskByOrderSn(orderSn);
        Long id = task.getId();
        //按照工作单找到所有没有解锁的库存(状态为1)，进行解锁
        List<WareOrderTaskDetailEntity> entities = orderTaskDetailService.list(new QueryWrapper<WareOrderTaskDetailEntity>()
                .eq("task_id", id)
                .eq("lock_status", 1));
        //分别解锁每一项库存
        for (WareOrderTaskDetailEntity entity : entities) {
            unLockStock(entity.getSkuId(),entity.getWareId(),entity.getSkuNum(),entity.getId());
        }
    }

    //解锁库存
    private void unLockStock(Long skuId, Long wareId, Integer num, Long taskDetailId) {
        wareSkuDao.unlockStock(skuId, wareId, num);
        //更新库存工作单的状态
        WareOrderTaskDetailEntity entity = new WareOrderTaskDetailEntity();
        entity.setId(taskDetailId);
        //变更状态为已解锁
        entity.setLockStatus(2);
        orderTaskDetailService.updateById(entity);
    }
}


//仓库有库存
@Data
class SkuWareHasStock {
    private Long skuId;
    private Integer num; //多少件
    private List<Long> wareId;   //仓库id
}